<template>
  <div class="content-box-full">
    <ContainerBox>
      <template #header>
        <el-form @keyup.enter.native="handleSearch" :model="searchForm" label-width="auto" inline>
          <el-row>
            <el-col :span="6">
              <el-form-item label="设备编号:" prop="equipmentNo">
                <el-input
                  placeholder="空格分隔可以查询多个设备"
                  v-model="searchForm.equipmentNo"
                  type="text"
                  autocomplete="off"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="设备名称:" prop="equipmentName">
                <el-input v-model="searchForm.equipmentName" type="text" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="食堂:" prop="canteenName">
                <el-popover
                  popper-class="form-item-popper"
                  placement="bottom-start"
                  trigger="click"
                >
                  <el-tree
                    class="common-el-tree hx-scroll"
                    :data="canteenTreeData"
                    node-key="id"
                    ref="searchCanteenTreeRef"
                    :default-expand-all="true"
                    :highlight-current="true"
                    :props="{
                      children: 'treeNode',
                      label: 'name',
                    }"
                    @check-change="searchCheckChange"
                    show-checkbox
                    :expand-on-click-node="false"
                  >
                  </el-tree>
                  <template #reference>
                    <el-input
                      v-model="searchForm.canteenCheckNames"
                      readonly
                      placeholder="点击勾选查询食堂"
                      class="menu-list__input"
                    ></el-input>
                  </template>
                </el-popover>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="设备状态:" prop="equipmentStatus">
                <el-select class="inline-select" v-model="searchForm.equipmentStatus">
                  <el-option
                    v-for="item in STATUS_LIST"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button
              v-prevent-reclick
              v-permission="'hire:equipment:list'"
              type="primary"
              @click="handleSearch"
              >查询
            </el-button>
            <el-button @click="handleAdd" v-permission="'hire:equipment:save'" v-prevent-reclick
              >新增
            </el-button>
          </el-form-item>
        </el-form>
      </template>
      <template #default>
        <el-table
          :data="tableData"
          :empty-text="isLoadingTable ? '加载中...' : '暂无数据'"
          class="table-box"
          height="100%"
          stripe
          fit
          border
          highlight-current-row
        >
          <el-table-column type="index" align="center" label="序号" width="80"></el-table-column>
          <el-table-column label="设备编号" align="center" min-width="120" prop="equipmentNumber">
          </el-table-column>
          <el-table-column label="设备名称" align="center" min-width="120" prop="equipmentName">
          </el-table-column>
          <el-table-column label="食堂" align="center" min-width="120" prop="canteen">
          </el-table-column>
          <el-table-column label="IP地址" align="center" min-width="100" prop="equipmentIp">
          </el-table-column>
          <el-table-column label="消费时段" align="center" min-width="120" prop="consumptionPeriod">
          </el-table-column>
          <el-table-column label="网络状态" align="center" min-width="100" prop="ipAddress">
          </el-table-column>
          <el-table-column label="设备序列号" align="center" min-width="100" prop="serialNumber">
          </el-table-column>
          <el-table-column label="设备状态" align="center" min-width="100" prop="ipAddress">
            <template #default="{ row }">
              <el-tag size="small" v-if="row.status === 1">正常</el-tag>
              <el-tag size="small" v-else type="warning">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" min-width="240">
            <template #default="{ row, $index }">
              <el-button v-permission="'hire:equipment:update'" @click="editRow(row)"
                >编辑
              </el-button>
              <el-button v-permission="'hire:equipment:editStatus'" @click="editStatus(row, $index)"
                >{{ row.status ? '禁用' : '启用' }}
              </el-button>
              <el-button v-permission="'hire:equipment:delete'" @click="deleteRow(row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <CommonPaging
          :total="tableTotal"
          :current-page="pageNum"
          @currentChange="handleCurrentChange"
          @sizeChange="handleSizeChange"
        ></CommonPaging>
      </template>
    </ContainerBox>
    <el-dialog
      lock-scroll
      top="10vh"
      class="common-el-dialog"
      v-model="showDialog"
      :title="isEdit ? '编辑设备' : '新增设备'"
      width="600"
      @close="handleClose"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRules"
        label-width="100px"
        status-icon
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编号:" prop="equipmentNo">
              <el-input
                :disabled="isEdit"
                v-model="dataForm.equipmentNo"
                type="text"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称:" prop="equipmentName">
              <el-input v-model="dataForm.equipmentName" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="IP地址:" prop="ipAddress">
              <el-input v-model="dataForm.ipAddress" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联食堂" prop="canteenCheckNames">
              <el-popover popper-class="form-item-popper" placement="bottom-start" trigger="click">
                <el-tree
                  class="common-el-tree hx-scroll"
                  :data="canteenTreeData"
                  node-key="id"
                  ref="canteenTreeRef"
                  :default-expand-all="true"
                  :highlight-current="true"
                  :props="{
                    children: 'treeNode',
                    label: 'name',
                    disabled: setNodeDisabled,
                  }"
                  @check-change="checkChange"
                  show-checkbox
                  :filter-node-method="filterTreeNode"
                  :expand-on-click-node="false"
                >
                </el-tree>
                <template #reference>
                  <el-input
                    v-model="dataForm.canteenCheckNames"
                    readonly
                    placeholder="点击勾选关联食堂"
                    class="menu-list__input"
                  ></el-input>
                </template>
              </el-popover>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="消费时段:" prop="consumptionPeriod">
              <el-select filterable clearable v-model="dataForm.consumptionPeriod">
                <el-option
                  v-for="item in consumptionContentList"
                  :key="item.id"
                  :value="item.code"
                  :label="`${item.code}-${item.name}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消费等级:" prop="consumptionLevel">
              <el-select filterable clearable v-model="dataForm.consumptionLevel">
                <el-option
                  v-for="item in consumptionLevelList"
                  :key="item.id"
                  :value="item.levelCode"
                  :label="`${item.levelCode}-${item.name}`"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行政负责人:" prop="hrDirectorName">
              <el-input v-model="dataForm.hrDirectorName" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IT责任人:" prop="ITDirectorName">
              <el-input v-model="dataForm.ITDirectorName" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备序列号:" prop="equipmentSeriesNo">
              <el-input v-model="dataForm.equipmentSeriesNo" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装位置:" prop="installPosition">
              <el-input v-model="dataForm.installPosition" type="text" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" v-prevent-reclick @click="handleFormSubmit"> 确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import ContainerBox from '@/components/base/ContainerBox.vue'
import { ref, onMounted, computed, nextTick } from 'vue'
import CommonPaging from '@/components/base/CommonPaging.vue'
import { STATUS_LIST } from '@/utils/systemConfig.js'
import message from '@/utils/elMessage.js'
import { usePublicStore } from '@/stores/publicInfo.js'
import equipmentInfoApi from '@/api/equipmentInfoApi.js'

onMounted(() => {
  fetchList()
})
const publicStore = usePublicStore()
const isEdit = computed(() => dialogType.value === 'edit')
const canteenTreeData = computed(() => publicStore.sysAreaEntityList)
const searchForm = ref({
  equipmentNo: '', //设备编号
  equipmentName: '', //设备名称
  canteenCheckNames: '', //食堂名称
  canteenCheckIds: [], //食堂ids
  equipmentStatus: 1, //设备状态
})
const searchCanteenTreeRef = ref(null)
const pageNum = ref(1)
const pageSize = ref(10)

function searchCheckChange() {
  const checkLeafNodes = searchCanteenTreeRef.value.getCheckedNodes(true, false)
  searchForm.value.canteenCheckNames = checkLeafNodes.map((el) => el.name).join('、')
  searchForm.value.canteenCheckIds = searchCanteenTreeRef.value.getCheckedKeys(true)
}

//查询
function handleSearch() {
  handleCurrentChange(1)
}

// 列表数据
const isLoadingTable = ref(false)
const tableData = ref([])
const tableTotal = ref(0)

function editStatus(row, rowIndex) {
  const newStatus = row.status ? 0 : 1
  equipmentInfoApi
    .editStatus({
      id: row.id,
      status: newStatus,
    })
    .then((res) => {
      if (res.code === 0) {
        message.success(res.msg)
        tableData.value[rowIndex]['status'] = newStatus
      } else {
        message.warning(res.msg)
      }
    })
}

function editRow(row) {
  equipmentInfoApi.check(row.id).then(async (res) => {
    if (res.code === 0) {
      const {
        id,
        equipmentNumber,
        equipmentName,
        equipmentIp,
        canteen,
        consumptionLevel,
        consumptionPeriod,
        xzPerson,
        itPerson,
        serialNumber,
        location,
      } = res.equipment || {}
      dataForm.value.id = id
      dataForm.value.equipmentNo = equipmentNumber
      dataForm.value.equipmentName = equipmentName
      dataForm.value.ipAddress = equipmentIp
      // dataForm.value.canteenCheckNames = '';
      // dataForm.value.canteenCheckIds = [+canteen];
      // dataForm.value.consumptionPeriod = consumptionPeriod;
      // dataForm.value.consumptionLevel = consumptionLevel;
      dataForm.value.hrDirectorName = xzPerson
      dataForm.value.ITDirectorName = itPerson
      dataForm.value.equipmentSeriesNo = serialNumber
      dataForm.value.installPosition = location

      await beforeOpenDialog()
      dialogType.value = 'edit'
      showDialog.value = true
      nextTick(() => {
        canteenTreeRef.value.filter()
        canteenTreeRef.value.setCheckedKeys([+canteen])
        dataForm.value.consumptionPeriod = consumptionPeriod
        dataForm.value.consumptionLevel = consumptionLevel
      })
    } else {
      message.warning(res.msg)
    }
  })
}

function deleteRow(row) {
  if (row.id) {
    message.confirm('您是否确定要删除该设备信息?', '提示').then(() => {
      equipmentInfoApi
        .delete([row.id])
        .then((res) => {
          if (res.code === 0) {
            message.success(res.msg)
            fetchList()
          } else {
            message.warning(res.msg)
          }
        })
        .catch((error) => {
          console.error(error.messages)
        })
    })
  }
}

function fetchList() {
  isLoadingTable.value = true
  tableData.value = []
  const params = {
    page: pageNum.value,
    limit: pageSize.value,
    equipmentNumber: searchForm.value.equipmentNo,
    equipmentName: searchForm.value.equipmentName,
    canteens: searchForm.value.canteenCheckIds.join(','),
    status: searchForm.value.equipmentStatus,
  }
  equipmentInfoApi
    .fetchList(params)
    .then((res) => {
      if (res.code === 0) {
        const data = res.page || {}
        tableTotal.value = data.totalCount || 0
        tableData.value = data.list || []
      } else {
        message.warning(res.msg)
      }
    })
    .finally(() => {
      isLoadingTable.value = false
    })
}

function handleCurrentChange(val) {
  pageNum.value = val
  fetchList()
}

function handleSizeChange(val) {
  pageSize.value = val
  pageNum.value = 1
  fetchList()
}

// 新增食堂相关
const showDialog = ref(false)
const dialogType = ref('add')
const dataFormRef = ref(null)
const dataForm = ref({
  id: '', //行id 用于编辑
  equipmentNo: '', //设备编号
  equipmentName: '', //设备名称
  ipAddress: '', //IP地址
  canteenCheckNames: '', //食堂中文名称
  canteenCheckIds: [], //食堂选中节点数组
  consumptionPeriod: '', //消费时段
  consumptionLevel: '', //消费等级
  hrDirectorName: '', //行政负责人
  ITDirectorName: '', //IT责任人
  equipmentSeriesNo: '', //设备序列号
  installPosition: '', //安装位置
})
const dataRules = ref({
  equipmentNo: [
    { required: true, message: '设备编号不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '设备编号不可以为空',
      trigger: 'change',
    },
  ],
  equipmentName: [
    { required: true, message: '设备名称不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '设备名称不可以为空',
      trigger: 'change',
    },
  ],
  ipAddress: [
    { required: true, message: 'IP地址不可以为空', trigger: 'blur' },
    {
      required: true,
      message: 'IP地址不可以为空',
      trigger: 'change',
    },
  ],
  canteenCheckNames: [
    { required: true, message: '食堂不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '食堂不可以为空',
      trigger: 'change',
    },
  ],
  consumptionPeriod: [
    { required: true, message: '消费时段不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '消费时段不可以为空',
      trigger: 'change',
    },
  ],
  consumptionLevel: [
    { required: true, message: '消费等级不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '消费等级不可以为空',
      trigger: 'change',
    },
  ],
  hrDirectorName: [
    { required: true, message: '行政负责人不可以为空', trigger: 'blur' },
    {
      required: true,
      message: '行政负责人不可以为空',
      trigger: 'change',
    },
  ],
  ITDirectorName: [
    { required: true, message: 'IT责任人不可以为空', trigger: 'blur' },
    {
      required: true,
      message: 'IT责任人不可以为空',
      trigger: 'change',
    },
  ],
})
const consumptionContentList = ref([])
const consumptionLevelList = ref([])
//食堂组织相关
const canteenTreeRef = ref(null)
//有权限的节点idlist
const filterAreaTree = ref([])

function filterTreeNode(value, data) {
  return filterAreaTree.value.includes(data.id)
}

//新增食堂只能选中一个节点
function setNodeDisabled(data, node) {
  if (!node.isLeaf) {
    return true
  }
  const canteenCheckIds = dataForm.value.canteenCheckIds || []
  if (canteenCheckIds.length) {
    return !canteenCheckIds.includes(data.id)
  } else {
    return false
  }
}

//关联食堂勾选改变
function checkChange() {
  const checkLeafNodes = canteenTreeRef.value.getCheckedNodes(true, false)
  dataForm.value.canteenCheckNames = checkLeafNodes.map((el) => el.name).join('、')
  dataForm.value.canteenCheckIds = canteenTreeRef.value.getCheckedKeys(true)
}

async function beforeOpenDialog() {
  filterAreaTree.value = await filterAreaSelect()
  const { consumptionPlanService = [], consumptionLevel = [] } = await fetchConsumptionSelect()
  consumptionContentList.value = consumptionPlanService
  consumptionLevelList.value = consumptionLevel
}

//新增
async function handleAdd() {
  await beforeOpenDialog()
  dialogType.value = 'add'
  showDialog.value = true
  nextTick(() => {
    canteenTreeRef.value.filter()
  })
}

function handleClose() {
  dataFormRef.value.resetFields()
  canteenTreeRef.value.setCheckedKeys([])
}

function handleFormSubmit() {
  dataFormRef.value.validate((bool) => {
    if (bool) {
      const isAdd = dialogType.value === 'add'
      const params = {
        id: isAdd ? undefined : dataForm.value.id,
        equipmentNumber: dataForm.value.equipmentNo,
        equipmentName: dataForm.value.equipmentName,
        equipmentIp: dataForm.value.ipAddress,
        canteen: dataForm.value.canteenCheckIds.join(),
        consumptionPeriod: dataForm.value.consumptionPeriod,
        consumptionLevel: dataForm.value.consumptionLevel,
        xzPerson: dataForm.value.hrDirectorName,
        itPerson: dataForm.value.ITDirectorName,
        serialNumber: dataForm.value.equipmentSeriesNo,
        location: dataForm.value.installPosition,
      }
      const fetchApi = isAdd ? equipmentInfoApi.save : equipmentInfoApi.update
      fetchApi(params).then((res) => {
        if (res.code === 0) {
          message.success(res.msg)
          showDialog.value = false
          if (isAdd) {
            handleCurrentChange(1)
          } else {
            fetchList()
          }
        } else {
          message.warning(res.msg)
        }
      })
    }
  })
}

async function filterAreaSelect() {
  try {
    const res = await equipmentInfoApi.filterAreaSelect()
    if (res.code === 0) {
      return (res.areaCodes || []).map(Number)
    } else {
      message.warning(res.msg)
      throw new Error(res.msg || '获取食堂组织权限信息失败！')
    }
  } catch (error) {
    console.error(error.messages)
    throw error
  }
}

//获取消费时段、消费等级下拉list
async function fetchConsumptionSelect() {
  try {
    const res = await equipmentInfoApi.fetchConsumptionSelect()
    if (res.code === 0) {
      return res.data || {}
    } else {
      message.warning(res.msg)
      throw new Error(res.msg || '获取消费时段、消费等级信息失败！')
    }
  } catch (error) {
    console.error(error.messages)
    throw error
  }
}
</script>

<style scoped lang="scss"></style>
